<?php

namespace App\Console\Commands;

use App\Imports\MultipleImport;
use App\Models\Employee;
use App\Models\JobType;
use App\Models\Rbac\User;
use App\Models\Rbac\UserRole;
use App\Models\UserJobType;
use Illuminate\Console\Command;
use Maatwebsite\Excel\Facades\Excel;

class AddEmployee extends Command
{
    /**
     * 批量添加员工
     * php artisan command:addemployee
     * @var string
     */
    protected $signature = 'command:addemployee';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Command description';

    /**
     * Execute the console command.
     *
     * @return int
     */
    public function handle()
    {
        $file = public_path('excel').'/员工.xlsx';//获取文件路径
        $import = new MultipleImport(3);
        Excel::import($import, $file);
        $results = $import->sheet[0]->data->toArray();
        //$results2 = $import->sheet[1]->data->toArray();
        //$results3 = $import->sheet[2]->data->toArray();
        //dd($results,$results2,$results3);
        unset($results[0]);
        unset($results[1]);
        foreach($results as $k=>$v){
            $this->info('导入：员工姓名='.$v[1].";工种=".$v[2].";手机号=".$v[3]);
            //$job_obj = JobType::updateOrCreate(['job_type'=>$v[2]],['job_type'=>$v[2]]);
            $job_type = JobType::where('job_type',$v[2])->first();

            $username = $v[1];
            $user = User::where('username',$username)->first();
            if(!$user){
                $user = new User();
                $user->username = $v[1];
                $user->password = 88888888;
                $user->phone = $v[3];
                $user->company_name = $v[1];
                $user->parent_username = 'zjzl';
                $user->save();
            }

            $where = ['user_id'=>$user->id];
            if(in_array($v[2],['销售部','销售经理'])){
                $role_id = 3;
            }
            UserRole::updateOrCreate($where,['role_id'=>$role_id??16]);
            if(!$job_type){
                continue;
            }
            $employee_info = [
                "employee_name" => $user['username'],
                "user_id"=>$user->id,
                "phone" => $v[3],
                'job_type_id'=>$job_type->id,
                "address" => '',
                "id_card" => '',
                "native_place" => '',
                "emergency_contact" => '',
                "emergency_contact_phone" => '',
                "card_number" => null,
                "base_pay" => '',
                "hiredate" => '',
                "submit_way" => '',
            ];
            Employee::updateOrCreate($where,$employee_info);
        }
        $this->info("结束");


    }
}
